<?php

namespace mybackend\controllers\official;

use Yii;
use mybackend\controllers\BaseController;
use common\services\official\SubscribeService;
use yii\helpers\Json;
use common\error\ErrorCode;


class SubscribeController extends BaseController {
    
    public $_subscribeService;
    
    public function __construct($id, $module, SubscribeService $SubscribeService, $config = []) {
        $this->_subscribeService = $SubscribeService;
        parent::__construct($id, $module, $config);
    }
    
    public function beforeAction($action) {
        return true;
    }
    
    /**
     * 预约记录
     */
    public function actionRecordSubscribe ($jsonp=0) {
        $data['source'] = Yii::$app->request->request('source');
        $data['name'] = htmlspecialchars(Yii::$app->request->request('name'));
        $data['city'] = htmlspecialchars(Yii::$app->request->request('city'));
        $data['company'] = htmlspecialchars(Yii::$app->request->request('company'));
        $data['tel'] = htmlspecialchars(Yii::$app->request->request('tel'));
        $this->_subscribeService->saveBepeak($data);
        
        $this->handleReturn($jsonp, array('success' => 1));
    }

    /**
     * 获取目录列表
     * @param int $jsonp
     */
    public function actionGetDirList ($jsonp = 0) {
        $data = $this->_subscribeService->getDirList();
        $this->handleReturn($jsonp, array('data' => $data));
    }
    
    /**
     * 获取文章列表
     */
    public function actionGetArticleList ($jsonp=0) {
        $offset = Yii::$app->request->request('offset', 0); // 分页下标
        $limit = Yii::$app->request->request('limit', 10); // 每页条数
        $dir = Yii::$app->request->request('dir'); // 分类
        $data = $this->_subscribeService->getArticleList($offset, $limit, $dir);
        $sum = $this->_subscribeService->getArticleCount($dir);

        $this->handleReturn($jsonp, array('data' => $data, 'sum' => $sum));
    }
    
    /**
     * 获取文章
     */
    public function actionGetArticle ($jsonp=0) {
        $id = $offset = Yii::$app->request->request('id', 0);
        if ($id == 0) {
            $this->errorParam();
        }
        $data = $this->_subscribeService->getArticle($id);
        $tempPerv = $this->_subscribeService->getArticle($id, 1, 's',$data['dir_id']);
        $perv['a_id'] = $tempPerv['a_id'];
        $perv['title'] = $tempPerv['title'];
        $tempNext = $this->_subscribeService->getArticle($id, 1, 'b',$data['dir_id']);
        $next['a_id'] = $tempNext['a_id']; 
        $next['title'] = $tempNext['title'];
        $this->handleReturn($jsonp, array('article' => $data, 'prev' => $perv, 'next' => $next));
    }
    
    
    public function handleReturn ($jsonp, $data) {
        if ($jsonp !== 0) {
            header('Content-type: application/javascript; charset=utf-8'); 
            die("var ".$jsonp."=".Json::encode($data));
        } else {
            $this->json($data, $jsonp);
        }
    }

}